<!--
 * @Date: 2023-07-31 14:01:38
 * @LastEditors: lijingang
 * @LastEditTime: 2023-07-31 14:28:18
 * @FilePath: /ds-brain-web/src/views/login/components/ImgVerification.vue
-->
<template>
  <div>
    <sec-input
      v-model="code"
      size="small"
      :maxlength="len"
      auto-complete="off"
      placeholder="请输入图形验证码"
      @input="change"
    >
      <i slot="prefix" class="icon-yanzhengma"></i>
    </sec-input>
    <div ref="img" v-loading="loaded" class="login-code global-login-code">
      <img
        :src="src"
        :class="[loaded ? 'show' : 'hidden', 'login-code-img']"
        @click="refreshCode"
        @load="fetchImg"
      />
    </div>
  </div>
</template>
<style lang="scss" scope></style>
<script>
import http from '@/utils/http'

export default {
  name: 'ImgVerification',
  props: {
    change: {
      type: Function,
      default: () => {}
    },
    refreshRandomStr: {
      type: Function,
      default: () => {}
    },
    appCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      len: 8,
      code: '',
      randomStr: '',
      src: '',
      loaded: false
    }
  },
  computed: {},
  mounted() {},
  created() {
    this.refreshCode()
  },
  methods: {
    fetchImg() {
      this.loaded = false
    },
    getUrl() {
      return (
        process.env.VUE_APP_BASE_API +
        http.getImgVerificationCode.url +
        `?randomStr=${this.randomStr}&appCode=${this.appCode}`
      )
    },
    refreshCode() {
      this.randomStr = Math.random(Date.now()).toString(36).slice(-8)
      // 同步到父组件
      this.refreshRandomStr(this.randomStr)
      this.loaded = true
      this.src = ''
      this.src = this.getUrl()
    }
  }
}
</script>
